<template>
	<view class="unbind-page">
		<Tips title="小贴士" :des="des" />
		<view class="unbind-content">
			<view class="unbind-title">临时解绑时间管理</view>
			<view class="time">
				<view class="time-wrap">
					<view class="remove-bottom-line base-item-time" style="display: flex;">
						<image src="/static/icon/clock.png" class="clock"  />
						<view class="title flex-3">开始时间</view>
						<view class="right-select-time flex-5">
							<picker mode="time" :value="time"  @change="bindTimeChange">
								<view class="input-time">{{time == '请选择开始时间' ? '' : currentYMD()}} {{time}}</view>
							</picker>
							<image src="/static/icon/arrow-right.png" class="arrow" /> 
						</view>
					</view>
					<view class="remove-bottom-line base-item-time" style="display: flex;">
						<image src="/static/icon/clock.png" class="clock" />
						<view class="title flex-3">结束时间</view>
						<view class="right-select-time flex-5">
							<picker mode="time" :value="endTime"  @change="bindEndTimeChange">
								<view class="input-time">{{endTime == '请选择结束时间' ? '' : currentYMD()}} {{endTime}}</view>
							</picker>
							<image src="/static/icon/arrow-right.png" class="arrow" />
						</view>
					</view>
				</view>
				<view class="time-lang">解绑时长： {{res}}</view>
			</view>
		</view>
		<view class="footer">
			<button class="base-btn unbind-btn" color="#ec6d67" @click="delteTimeBind">结束临时解绑</button>
			<button class="base-btn save-btn" color="#62c58e"  @click="onSave" >保存提交</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted } from 'vue'
	import Tips from "@/components/tips/index.vue"
	import Clock from "@/components/icons/clock.vue"
	import { homeServer } from '@/common/index'
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import dayjs from "@/plugins/dayjs.js"
	
	const studentStore = useStudentListStore();
	const curStd = computed(() => studentStore.currentStudent);
	const haveTime = ref(false); // true: 1.已经从接口拉取到时间了 2. 点击了保存那么此时也是有时间的，不能直接去改时间要先“结束临时解绑”才可以去设置时间 false: 可以取设置时间
	
	const currentYMD = () => {
		// 获取当前日期
		const now = dayjs();
		return now.format('YYYY/MM/DD');
	}
	function extractTime(dateTimeStr) {  
	 // 定义一个正则表达式来匹配 "HH:mm" 格式  
	  const timeRegex = /^\d{2}:\d{2}$/;  
	  // 检查字符串是否符合时间格式  
	  if (timeRegex.test(dateTimeStr)) {  
		// 如果是时间格式，直接返回  
		return dateTimeStr;  
	  }  
	  // 定义一个正则表达式来匹配 "YYYY-MM-DD HH:mm" 格式  
	  const dateTimeRegex = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;  
	  // 检查字符串是否符合日期时间格式  
	  if (dateTimeRegex.test(dateTimeStr)) {  
	    // 使用字符串的 split 方法来分割字符串，并获取时间部分  
	    const parts = dateTimeStr.split(' ');  
	    return parts[1]; // 返回时间部分  
	  } else {  
	    // 如果不符合格式，返回空字符串  
	    return '';  
	  }  
	}  
	// 获取当前是多少小时，多少分 格式为 HH:mm
	function getCurrentTimeFormatted() {  
	    const now = new Date();  
	    const hours = now.getHours().toString().padStart(2, '0'); // 获取小时数，不足两位前面补0  
	    const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟数，不足两位前面补0  
	    return `${hours}:${minutes}`; // 拼接字符串并返回  
	}
	
	// 获取临时解绑
	const getTemporaryUnBindInfo = async () => {
		const studentId = curStd.value?.id;
		if(studentId){
			try{
				const {status, data} = await homeServer.getTemporaryUnBindInfo({studentId})
				if(status === '200'){
					if(data == null) {
						console.log('getCurrentTimeFormatted()', getCurrentTimeFormatted())
						time.value = getCurrentTimeFormatted()
						endTime.value = '请选择结束时间'
						console.log('getCurrentTimeFormatted()', time.value)
					} else {
						time.value =  extractTime(data.startTime)
						endTime.value = extractTime(data.endTime)
						haveTime.value = true;
						queryRes(time.value, endTime.value)
					}
				}
			}catch(e){
				console.log(e)
				//TODO handle the exception
			}
		} else {
			console.log('没有绑定学生')
		}
	}
	// 返回首页
	const goBackHomePage = () => {
		uni.navigateBack()
	}
	
	// 提交临时解绑
	const temporaryUnBind = async () => {
		const studentId = curStd.value?.id;
		if(studentId){
			try{
				const params = {
					studentId,
					startTime: dayjs().format('YYYY-MM-DD') +" " + time.value,
					endTime: dayjs().format('YYYY-MM-DD') + " " + endTime.value
				};
				const {status, data} = await homeServer.temporaryUnBind(params);
				if(status === '200'){
					haveTime.value = true
					uni.showToast({
						title:'保存成功',
						icon:"success",
						success() {
							setTimeout(() => goBackHomePage(), 1000)
						}
					})
				}
				if(status === '200'){
					console.log('临时解绑的数据', data)
				}
			}catch(e){
				console.log(e)
				//TODO handle the exception
			}
		} else {
			console.log('没有绑定学生')
		}
	}
	
	
	// 删除临时解绑
	const finishTemporaryUnBind = async () => {
		const studentId = curStd.value?.id;
		if(studentId){
			try{
				const {status, data} = await homeServer.finishTemporaryUnBind({studentId});
				if(status === '200'){
					haveTime.value  = false
					uni.showToast({
						title:'删除临时解绑成功',
						icon:"success",
						duration:2000,
						success() {
							setTimeout(() => goBackHomePage(), 1000)
						}
					})
				}
				if(status === '200'){
					console.log('临时解绑的数据', data)
				}
			}catch(e){
				console.log(e)
				//TODO handle the exception
			}
		} else {
			console.log('没有绑定学生')
		}
	}
	
	const onSave = () => {
		if(haveTime.value){
			uni.showToast({
				title:"请先结束临时解绑",
				icon:"none",
				duration:1000
			})
			return
		}
		const start_time = time.value; 
		const end_time = endTime.value;
		const isNotEmpt = v => v.includes(":");
		const timeIsEmpt = v => v === "" || v === "请选择结束时间" || v === "请选择开始时间" || v === undefined || v === null || !v.includes(":")
		if(timeIsEmpt(start_time)){
			uni.showToast({
				title:"请选择开始时间",
				icon: "none"
			})
			return
		}
		console.log('end_time--->', end_time)
		if(timeIsEmpt(end_time)){
			uni.showToast({
				title:"请选择结束时间",
				icon: "none"
			})
			return
		}
		
		// 开始时间不能大于结束时间
		if(!validateTime(time.value, endTime.value)){
			uni.showToast({
				title:"结束时间不能小于开始时间",
				icon: "none"
			})
			return;
		}
		if(isNotEmpt(start_time) && isNotEmpt(end_time)){
			temporaryUnBind();
		}
	}
	
	const delteTimeBind = () => {
		console.log("--->", time.value, endTime.value)
		const timeIsEmpt = v => v === "" || v === "请选择结束时间" || v === "请选择开始时间" || v === undefined || v === null || !v.includes(":")
		if(timeIsEmpt(endTime.value)){
			uni.showToast({
				title:"没有结束时间",
				icon: 'none'
			})
			return;
		}
		time.value = getCurrentTimeFormatted();
		endTime.value = "请选择时间";
		res.value = '-';
		finishTemporaryUnBind();
	}
	
	onMounted(() => {
		getTemporaryUnBindInfo();
	})
	
	
	const des = ref([
		"1.设定好解绑时间后，学生端在时间内处于临时解绑",
		"2. 可以通过结束临时解绑，提前取消解绑， 自动绑定",
		"3. 临时解绑后，孩子端不要管控， 例如可以打开系统设置等",
		{
			text: '4.使用帮助',
			type: 'temporaryUnbind'
		}
		])
	const res = ref("-");
	const queryRes = (s, e) => {
		const [s_s, s_e] = s.split(":").map(t => Number(t));
		const [e_s, e_e] = e.split(":").map(t => Number(t));
		let r = "";
		if(e_e > s_e || e_e == s_e){
			r = (e_s - s_s) + '小时' + (e_e - s_e) + '分钟'
		} else {
		  r = e_s - 1 - s_s + '小时' + (e_e + 60 - s_e) + '分钟'
		}
		res.value = r;
	}
	const validateTime = (s, e) =>{
		const [s_s, s_e] = s.split(":").map(t => Number(t));
		const [e_s, e_e] = e.split(":").map(t => Number(t));
		return e_s > s_s || (e_s === s_s && e_e > s_e);
	}
	const time = ref('请选择时间');
	const endTime = ref("请选择时间");
	const bindEndTimeChange = (e) => {
		if(haveTime.value){
			uni.showToast({
				title:"请先结束临时解绑",
				icon:"none",
				duration:1000
			})
			return
		}
		if(validateTime(time.value, e.detail.value)){
			endTime.value = e.detail.value
			queryRes(time.value, endTime.value)
		} else {
			uni.showToast({
				title:"结束时间不能小于开始时间",
				icon: "none"
			})
		}
	}
	const bindTimeChange = (e) => {
		console.log('haveTime.value', haveTime.value, endTime.value)
		const timeIsEmpt = v => v === "" || v === "请选择结束时间" || v === "请选择开始时间" || v === undefined || v === null || !v.includes(":")
		
		if(haveTime.value){
			uni.showToast({
				title:"请先结束临时解绑",
				icon:"none",
				duration:1000
			})
			return
		}
		
		if(timeIsEmpt(endTime.value)){ // 结束时间现在还没选
			if(validateTime(getCurrentTimeFormatted(), e.detail.value)){
				time.value = e.detail.value
				return;
			} else {
				uni.showToast({
					title:"开始时间应该大于或等于当前时间",
					icon: "none"
				})
				return;
			}
		}
		
		if(validateTime(e.detail.value, endTime.value)){
			time.value = e.detail.value
			queryRes(time.value, endTime.value)
		} else {
			uni.showToast({
				title:"开始时间不能大于结束时间",
				icon: "none"
			})
		}
		// time.value = e.detail.value
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f9fa;
	}
</style>

<style scoped lang="scss">
	.unbind-page {
		.unbind-content {
			margin-top: 40upx;
			background-color: #fff;
			border-radius: 16upx;
			padding: 40upx 40upx;

			.unbind-title {
				font-size: 30upx;
				font-weight: bold;
				color: #000;
				margin-bottom: 20upx;
			}
			.time{
				.title{
					margin-left: 10upx;
				}
				.right-select-time{
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
			.time-lang{
				margin-top: 40upx;
				width: 100%;
				color: #999999 ;
				text-align: center;
				font-size: 32upx;
			}
		}
		
		.footer{
			position: fixed;
			text-align: center;
			left: 0upx;
			right: 0upx;
			bottom: 60upx;
			margin: auto;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.base-btn{
				width: 45%;
				height: 112upx;
				line-height: 112upx;
				border-radius: 56upx;
				border: none;
				// outline-offset: none;
				outline: none;
				list-style: none;
				outline-width: 0;
				outline-style: none;
			}
			.unbind-btn{
				background-color: #FF6363;
				color: #FFFFFF;
			}
			.save-btn{
				background-color: #2BC888;
				color: #FFFFFF;
			}
		}
	}
</style>
<style lang="scss">
	.unbind-page {
		.footer{
			.van-button{
				width: 45%;				
			}
			.van-button:last-child{
				margin-left: 20upx;
			}
		}
	}
	
	
	.remove-bottom-line{
		.van-cell{
			background-color: #F7FBFE;
			border-radius: 44upx;
			margin-bottom: 20upx;
			&::after{
				display: none;
			}
		}
	}
	
	.arrow{
		width: 20px;
		height: 20px;
	}
	.clock{
		width: 16px;
		height: 16px;
	}
</style>


<style lang="scss" scoped>
	.time-wrap{
		// display: flex;
		// flex-direction: column;
	}
	
	.base-item-time{
		background-color: #F7FBFE;
		margin-bottom: 20upx;
		height: 80upx;
		border-radius: 40upx !important;
		display: flex !important;
		align-items: center;
		.right-select-time{
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		.title, .input-time{
			font-size: 32upx;
		}
		.flex-2{
			flex: 2;
		}
		.flex-3{
			flex: 3;
		}
		.flex-5{
			flex: 6;
			flex-shrink: 0;
		}
	}
</style>